<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/

// Define a destination
sleep(1);

$file_type = trim($_REQUEST['file_type']);

if( $file_type ==1 )
{
	$targetFolder = '/tmpfile'; // Relative to the root
	
	if (!empty($_FILES)) {
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$imgfile_name = $_FILES['Filedata']['name'];
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
		$NewFileName = date("ymdHis", time()).mt_rand(100,999);
		$targetFile = rtrim($targetPath,'/') . '/' . $NewFileName;
		$fs = explode('.', $imgfile_name);
		$targetFile = $targetFile.'.'.$fs[count($fs)-1];
		// Validate the file type
		$suffix = $_REQUEST['suffix'];
		$fileTypes = array();
		if($suffix == 1) $fileTypes = array('apk');
		if($suffix == 2) $fileTypes = array('xls');
		$fileParts = pathinfo($_FILES['Filedata']['name']);
		if (in_array($fileParts['extension'],$fileTypes)) {
			move_uploaded_file($tempFile,$targetFile);
			$res = date('Y').'/'.date('m').'/'.$NewFileName.'.'.$fs[count($fs)-1];
			
			echo json_encode(array('status'=>1,'data'=>$res));
			exit;
		}
		else
		{
			echo json_encode(array('status'=>0,'data'=>"上传文件格式错误(只能上传.$fileTypes[0]文件)"));
			exit;
		}
	}
}
else if($file_type ==2)
{
	$targetFolder = '/tmpimg'; // Relative to the root
	
	if (!empty($_FILES)) {
		
// 		deldir('../tmpimg/');
		
		$tempFile = $_FILES['Filedata']['tmp_name'];
		$imgfile_name = $_FILES['Filedata']['name'];
		
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
 		$NewFileName = date("ymdHis", time()).mt_rand(100,999);
		$targetFile = rtrim($targetPath,'/') . '/' . $NewFileName;
		$fs = explode('.', $imgfile_name);
		$targetFile = $targetFile.'.'.$fs[count($fs)-1];
		// Validate the file type
		$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
		$fileParts = pathinfo($_FILES['Filedata']['name']);
		
		if (in_array($fileParts['extension'],$fileTypes)) {
			move_uploaded_file($tempFile,$targetFile);
// 			$res = $targetFolder.'/'.$NewFileName.'.'.$fs[count($fs)-1];
			$res = $NewFileName.'.'.$fs[count($fs)-1];
			
			$tmp_img = '../tmpimg/'.$NewFileName.'.'.$fs[count($fs)-1];
			$file_size = getimagesize($tmp_img);
			$img_width = trim($_REQUEST['img_width']);
			$img_height = trim($_REQUEST['img_height']);
			if($file_size[0]==$img_width && $file_size[1]==$img_height)
			{
				echo json_encode(array('status'=>1,'data'=>$res));
			}
			else
			{
				echo json_encode(array('status'=>0,'data'=>'该类图片要求宽='.$img_width.',高='.$img_height));
			}
		} else {
			echo json_encode(array('status'=>0,'data'=>'上传的图片格式错误'));
		}
	}
}

function deldir($dir) {
	//先删除目录下的文件：
	$dh=opendir($dir);
	while ($file=readdir($dh)) {
		if($file!="." && $file!="..") {
			$fullpath=$dir."/".$file;
			if(!is_dir($fullpath)) {
				unlink($fullpath);
			} else {
				deldir($fullpath);
			}
		}
	}
}

?>